<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="back-btn" @tap="navigateBack">
        <text class="back-icon">←</text>
      </view>
      <view class="search-input">
        <input 
          type="text" 
          placeholder="搜索景点/酒店" 
          v-model="searchKey" 
          focus 
          @confirm="search"
        />
        <text class="clear-icon" v-if="searchKey" @tap="searchKey = ''">×</text>
      </view>
      <view class="search-btn" @tap="search">搜索</view>
    </view>
    
    <!-- 当前位置 -->
    <view class="current-location" v-if="!searchKey">
      <text class="location-icon">📍</text>
      <text>{{ currentCity }}</text>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="!searchKey && searchHistory.length > 0">
      <view class="history-header">
        <text class="section-title">搜索历史</text>
        <text class="clear-btn" @tap="clearHistory">清除</text>
      </view>
      <view class="history-list">
        <view 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @tap="searchKey = item; search()"
        >
          {{ item }}
        </view>
      </view>
    </view>
    
    <!-- 热门景点 -->
    <view class="hot-spots" v-if="!searchKey">
      <text class="section-title">热门景点</text>
      <view class="spot-grid">
        <view 
          class="spot-item" 
          v-for="(spot, index) in hotSpots" 
          :key="index"
          @tap="selectSpot(spot)"
        >
          {{ spot.name }}
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-results" v-if="searchKey && searchResults.length > 0">
      <view 
        class="result-item" 
        v-for="(result, index) in searchResults" 
        :key="index"
        @tap="selectSearchResult(result)"
      >
        <view class="result-icon">📍</view>
        <view class="result-info">
          <text class="result-name">{{ result.name }}</text>
          <text class="result-address">{{ result.address }}</text>
        </view>
      </view>
    </view>
    
    <!-- 无搜索结果 -->
    <view class="no-results" v-if="searchKey && searchResults.length === 0">
      <text class="no-result-icon">🔍</text>
      <text>没有找到"{{ searchKey }}"相关结果</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKey: '',
      currentCity: '北京',
      searchHistory: [],
      hotSpots: [],
      searchResults: []
    }
  },
  onLoad() {
    // 加载搜索历史
    const history = uni.getStorageSync('searchHistory');
    if (history) {
      this.searchHistory = JSON.parse(history);
    }
    
    // 添加完整的景点数据
    this.hotSpots = [
      { id: 1, name: '故宫博物院', address: '北京市东城区景山前街4号' },
      { id: 2, name: '颐和园', address: '北京市海淀区新建宫门路19号' },
      { id: 3, name: '八达岭长城', address: '北京市延庆区八达岭长城景区' },
      { id: 5, name: '天坛公园', address: '北京市东城区天坛路天坛公园' },
      { id: 6, name: '鸟巢', address: '北京市朝阳区国家体育场南路1号' },
      { id: 8, name: '北海公园', address: '北京市西城区文津街1号' }
    ];
    
    // 获取当前位置城市
    this.getCurrentCity();
  },
  methods: {
    navigateBack() {
      try {
        // 尝试返回上一页
        uni.navigateBack({
          fail: (err) => {
            console.error('导航返回失败，尝试重定向到地图页', err);
            // 如果返回失败，直接导航到地图页
            uni.redirectTo({
              url: '/pages/guide/map',
              fail: (err2) => {
                console.error('重定向到地图页也失败', err2);
                // 最后尝试跳转到首页
                uni.switchTab({
                  url: '/pages/index/index'
                });
              }
            });
          }
        });
      } catch (e) {
        console.error('返回导航异常', e);
        // 出现异常时，尝试跳转到地图页
        uni.redirectTo({
          url: '/pages/guide/map'
        });
      }
    },
    
    getCurrentCity() {
      // 这里可以使用定位API获取当前城市
      // 暂时使用默认值
    },
    
    search() {
      if (!this.searchKey.trim()) return;
      
      // 添加到搜索历史
      if (!this.searchHistory.includes(this.searchKey)) {
        this.searchHistory.unshift(this.searchKey);
        if (this.searchHistory.length > 10) {
          this.searchHistory.pop();
        }
        
        // 保存搜索历史到本地存储
        uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
      }
      
      // 跳转到地图页并传递搜索关键词
      uni.navigateBack({
        success: () => {
          // 延迟一下确保导航完成再传递参数
          setTimeout(() => {
            // 传递消息到上一页，通知搜索关键词
            uni.$emit('searchKeyword', { keyword: this.searchKey });
          }, 100);
        }
      });
    },
    
    clearHistory() {
      this.searchHistory = [];
      uni.removeStorageSync('searchHistory');
    },
    
    selectCity(city) {
      // 选择城市后返回上一页并传递选中的城市
      uni.navigateBack({
        success: () => {
          // 传递消息到上一页，通知切换城市
          setTimeout(() => {
            uni.$emit('changeCity', { city });
          }, 100);
        }
      });
    },
    
    selectSpot(spot) {
      // 选择景点后返回地图页并搜索该景点
      uni.navigateBack({
        success: () => {
          setTimeout(() => {
            uni.$emit('searchKeyword', { keyword: spot.name });
          }, 100);
        }
      });
    },
    
    selectSearchResult(result) {
      // 选择搜索结果后返回地图页
      uni.navigateBack({
        success: () => {
          setTimeout(() => {
            uni.$emit('searchKeyword', { keyword: result.name });
          }, 100);
        }
      });
    },
    
    // 模拟搜索接口
    getSearchResults(keyword) {
      if (!keyword) return [];
      
      const results = [];
      
      // 从热门景点中筛选匹配的结果
      this.hotSpots.forEach(spot => {
        if (spot.name.includes(keyword) || (spot.address && spot.address.includes(keyword))) {
          results.push(spot);
        }
      });
      
      // 添加一些额外的搜索结果
      const additionalSpots = [
        { id: 101, name: '北京动物园', address: '北京市西城区西直门外大街137号' },
        { id: 102, name: '北京植物园', address: '北京市海淀区香山南路' },
        { id: 103, name: '北京欢乐谷', address: '北京市朝阳区东四环小武基东路欢乐谷景区' },
        { id: 104, name: '南锣鼓巷', address: '北京市东城区南锣鼓巷' }
      ];
      
      additionalSpots.forEach(spot => {
        if (spot.name.includes(keyword) || spot.address.includes(keyword)) {
          results.push(spot);
        }
      });
      
      return results;
    }
  },
  watch: {
    searchKey(newVal) {
      // 实时搜索
      this.searchResults = this.getSearchResults(newVal);
    }
  }
}
</script>

<style lang="scss">
.search-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      font-size: 36rpx;
      font-weight: bold;
    }
  }
  
  .search-input {
    flex: 1;
    position: relative;
    height: 70rpx;
    margin: 0 20rpx;
    
    input {
      width: 100%;
      height: 100%;
      background: #f5f5f5;
      border-radius: 35rpx;
      padding: 0 60rpx 0 30rpx;
      font-size: 28rpx;
    }
    
    .clear-icon {
      position: absolute;
      right: 20rpx;
      top: 50%;
      transform: translateY(-50%);
      font-size: 32rpx;
      color: #999;
    }
  }
  
  .search-btn {
    font-size: 28rpx;
    color: #007AFF;
  }
}

.current-location {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: #fff;
  margin-top: 20rpx;
  
  .location-icon {
    margin-right: 20rpx;
    font-size: 32rpx;
  }
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.search-history {
  margin-top: 20rpx;
  padding: 30rpx;
  background: #fff;
  
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .clear-btn {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .history-list {
    display: flex;
    flex-wrap: wrap;
    
    .history-item {
      background: #f5f5f5;
      border-radius: 30rpx;
      padding: 10rpx 30rpx;
      margin: 0 20rpx 20rpx 0;
      font-size: 26rpx;
      color: #666;
    }
  }
}

.hot-spots {
  margin-top: 20rpx;
  padding: 30rpx;
  background: #fff;
  
  .spot-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10rpx;
    
    .spot-item {
      width: calc(33.33% - 20rpx);
      height: 80rpx;
      background: #f5f5f5;
      border-radius: 10rpx;
      margin: 0 10rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #333;
      text-align: center;
    }
  }
}

.search-results {
  background: #fff;
  padding: 0 30rpx;
  
  .result-item {
    display: flex;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    .result-icon {
      margin-right: 20rpx;
      color: #007AFF;
      font-size: 32rpx;
    }
    
    .result-info {
      flex: 1;
      
      .result-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }
      
      .result-address {
        font-size: 24rpx;
        color: #999;
        display: block;
      }
    }
  }
}

.no-results {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .no-result-icon {
    font-size: 80rpx;
    margin-bottom: 30rpx;
    color: #ddd;
  }
  
  text {
    font-size: 28rpx;
    color: #999;
  }
}
</style> 